package com.example.demo.lockAndSycn;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 创建资源类, 在资源类创建属性和操作方法
 */
class Ticket_lock {
    private static Integer NUMBER = 30;

    private static Lock lock = new ReentrantLock();

    public static void saleTicket() {
        lock.lock();
        try {
            if (NUMBER > 0) {
                System.out.println(Thread.currentThread().getName() + "正在买" + (NUMBER--) + "票" + ",剩下: " + NUMBER);
            } else {
                System.out.println("没票了");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}

public class ThreadDemo_lock {

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 15; i++) {
                Ticket_lock.saleTicket();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                Ticket_lock.saleTicket();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                Ticket_lock.saleTicket();
            }
        }, "CC").start();
    }
}
